<template>
  <div class="baseInfo">
    <div class="left">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item class="gaidong" label="学校名称" prop="name">
          <el-input
            style="width: 300px; margin-left: 20px"
            v-model="ruleForm.name"
            placeholder="请输入学校名称"
          ></el-input>
        </el-form-item>
        <el-form-item class="gaidong" label="类型" prop="region">
          <el-select
            style="width: 300px; margin-left: 20px"
            v-model="ruleForm.region"
            placeholder="请选择学校类型"
          >
            <el-option label="公办" value="公办"></el-option>
            <el-option label="民办" value="民办"></el-option>
          </el-select>
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="学校地址" prop="address">
          <!-- 省选择 -->
          <el-select
            style="width: 200px; margin: 0px 10px 0px 20px"
            v-model="ruleForm.province"
            placeholder="请选择省"
            @change="handleProvinceChange"
            clearable
          >
            <el-option
              v-for="province in provinceList"
              :key="province.value"
              :label="province.label"
              :value="province.value"
            >
            </el-option>
          </el-select>
          <!-- 市选择 -->
          <el-select
            style="width: 200px; margin: 0px 10px 0px 0px"
            v-model="ruleForm.city"
            placeholder="请选择市"
            @change="handleCityChange"
            clearable
            :disabled="!ruleForm.province"
          >
            <el-option
              v-for="city in cityList"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            ></el-option>
          </el-select>
          <!-- 区县选择 -->
          <el-select
            style="width: 200px; margin: 0px 10px 0px 0px"
            v-model="ruleForm.district"
            placeholder="请选择区（县）"
            clearable
            :disabled="!ruleForm.city"
          >
            <el-option
              v-for="district in districtList"
              :key="district.value"
              :label="district.label"
              :value="district.value"
            ></el-option>
          </el-select>
          <!-- 详细地址输入 -->
          <el-input
            v-model="ruleForm.detailAddress"
            placeholder="请输入详细地址"
            clearable
            style="width: 200px; margin: 0px 10px 0px 0px"
          ></el-input>
        </el-form-item>

        <el-form-item class="gaidong" label="学校联系人" prop="people">
          <el-input
            style="width: 300px; margin-left: 20px"
            v-model="ruleForm.people"
            placeholder="请输入学校联系人"
          ></el-input>
        </el-form-item>

        <el-form-item class="gaidong" label="联系方式" prop="way">
          <el-input
            style="width: 300px; margin-left: 20px"
            v-model="ruleForm.way"
            placeholder="请输入联系方式"
          ></el-input>
        </el-form-item>

        <el-form-item style="margin-top: 150px; position: relative; left: 10px">
          <el-button
            style="margin: 0px 30px 0px 0px"
            @click="resetForm('ruleForm')"
            >取消</el-button
          >
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="right">
      <el-upload
        action="#"
        :file-list="fileList"
        :auto-upload="false"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :limit="1"
        :on-change="handleFileChange"
      >
        <i class="el-icon-plus"></i>
        <div class="el-upload__tip" slot="tip">只支持jpg/png文件</div>
        <div class="tip" slot="tip">上传校徽、图片</div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
//引入省市区数据
const provinceList = [
  {
    label: "辽宁省",
    value: "辽宁省",
    cityList: [
      {
        label: "大连市",
        value: "大连市",
        districtList: [
          {
            label: "中山区",
            value: "中山区",
          },
          {
            label: "西岗区",
            value: "西岗区",
          },
        ],
      },
      {
        label: "本溪市",
        value: "本溪市",
        districtList: [
          {
            label: "平山区",
            value: "平山区",
          },
          {
            label: "溪湖区",
            value: "溪湖区",
          },
        ],
      },
    ],
  },
];

export default {
  data() {
    return {
      fileList: [], //上传文件列表

      provinceList: provinceList,
      cityList: [], //存储当前选中的
      districtList: [],
      ruleForm: {
        name: "",
        region: "",
        people: "",
        way: "",
        province: "", //选中的省
        city: "", //选中的市
        district: "", //选中的区县
        detailAddress: "", //详细地址
        address: "",
        photos: [], //存储base64格式照片
      },
      // 上传相关数据
      dialogVisible: false,
      dialogImageUrl: "",

      isEdit: false,
      editId: null,
      rules: {
        name: [
          { required: true, message: "请输入学校名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        region: [
          { required: true, message: "请选择学校类型", trigger: "change" },
        ],
        people: [
          { required: true, message: "请输入学校联系人", trigger: "blur" },
        ],
        way: [
          { required: true, message: "请输入联系方式", trigger: "blur" },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        address: [{ required: true, message: "请选择地址", trigger: "change" }],
        province: [{ required: true, message: "请选择省", trigger: "change" }],
        city: [{ required: true, message: "请选择市", trigger: "change" }],
        district: [
          { required: true, message: "请选择区县", trigger: "change" },
        ],
        detailAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //从本地存储加载已保存的图片
    const savedPhotos = localStorage.getItem("schoolPhotos");
    if (savedPhotos) {
      this.fileList = JSON.parse(savedPhotos);
    }
    console.log("BaseInfo组件已加载"); // 添加日志
  },
  methods: {
    // 省改变时，更新市列表
    handleProvinceChange(provinceValue) {
      const selectedProvince = this.provinceList.find(
        (item) => item.value === provinceValue
      );
      if (selectedProvince) {
        this.cityList = selectedProvince.cityList;
        this.ruleForm.city = ""; // 清空已选的市
        this.districtList = []; // 清空已选的区县
        this.ruleForm.district = "";
      } else {
        this.cityList = [];
        this.districtList = [];
      }
      //更新地址
      this.updateAddress();
    },
    // 市改变时，更新区县列表
    handleCityChange(cityValue) {
      const selectedCity = this.cityList.find(
        (item) => item.value === cityValue
      );
      if (selectedCity) {
        this.districtList = selectedCity.districtList;
        this.ruleForm.district = ""; // 清空已选的区县
      } else {
        this.districtList = [];
      }
      this.updateAddress = [];
    },
    //拼接地址并触发验证
    updateAddress() {
      const province = this.ruleForm.province;
      const city = this.ruleForm.city;
      const district = this.ruleForm.district;
      const detailAddress = this.ruleForm.detailAddress;
      //拼接完整地址
      this.ruleForm.address = `${province}${city}${district}${detailAddress}`;
      //手动触发address字段验证
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField("address");
      });
    },
    //移除照片
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.ruleForm.photos = [];
      localStorage.removeItem("schoolPhotos");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //处理文件变化
    handleFileChange(file, fileList) {
      const isImage = file.raw.type.indexOf("image/") === 0;
      const isLt2M = file.raw.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error("只能上传图片文件！");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过5MB!");
        return false;
      }
      //将文件转换为base64格式
      this.convertToBase64(file.raw);
      this.fileList = fileList.slice(-1); //只保留最新的一张图片
    },

    //将图片转换为base64格式
    convertToBase64(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        //保存base64到表单数据
        this.ruleForm.photos = [
          {
            name: file.name,
            url: e.target.result,
            size: file.size,
            type: file.type,
          },
        ];
      };
      reader.readAsDataURL(file);
    },

    //提交表单时保存所有数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //确保存储有效的图片url
          const photosToSave = this.fileList.map((file) => ({
            ...file,
            //添加永久性
            permanentUrl: file.url.startsWith("blob:")
              ? this.ruleForm.photos[0]?.url
              : file.url,
          }));

          //保存表单数据到localStorage
          localStorage.setItem("ruleForm", JSON.stringify(this.ruleForm));
          //保存图片数据到localStorage

          localStorage.setItem("schoolPhotos", JSON.stringify(photosToSave));

          this.$router.push({ name: "BaseImage" });
        
        }
      });
    },

    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    //   this.$router.push("/education/baseImage");
    // },
    resetForm() {
      this.$router.push("/education/baseImage");
    },
  },
};
</script>

<style lang="scss" scoped>
.baseInfo {
  background-color: #fff;
  border-radius: 10px;
  height: 100vh;
  min-height: 100vh;
  display: flex;
padding-top:20px ;
  justify-content: space-between;

  .baseInfo .gaidong {
    margin-right: 20px !important;
  }
  .right {
    display: flex;
    margin: 40px;
    .el-upload__tip {
      font-size: 17px;
    }
    .tip {
      position: relative;
      font-size: 14px;
      color: rgb(67, 65, 65);
      bottom: 80px;
      left: 20px;
    }
  }
}
</style>
